{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer, initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-00fde7534751>:11: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-00fde7534751>:29: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-00fde7534751>:32: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-00fde7534751>:49: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 27010, 27010, 26352, 26352, 26352, 15843, 15843, 18690,\n",
       "          16846, 12084, 11243, 10399, 10399, 10399, 10399, 17067, 31567,\n",
       "          29143, 25594, 25594, 25594, 25594, 25594,   209,   209,   209,\n",
       "          14074, 14074, 14074, 27422, 22091, 22091, 13153, 10120, 10120,\n",
       "          10120]],\n",
       " \n",
       "        [[    1,  4090,  9499,  9499,  4513,  8146,  8146,  8146, 14797,\n",
       "          14797, 16774, 16774, 16776, 16776, 16776,   381, 18044,  6453,\n",
       "          18432, 13834, 29884, 29794, 29794,  6422,  6422,  6422,  6422,\n",
       "          15892, 15892, 15892,  4184,  4184, 21205, 28975, 28975, 28562,\n",
       "          23045]],\n",
       " \n",
       "        [[    1, 17575,  1279,  6810,  6810, 25159, 21790, 21790, 18539,\n",
       "          18539, 18539,  3599,  3599, 21967, 21967, 21967, 16596, 16596,\n",
       "          16596, 12864, 12864,  6171,  6171,  5049,  6171,  5240,  9922,\n",
       "           5240, 10651, 10651, 10651, 10651, 20684, 20684, 10651, 16677,\n",
       "          16677]],\n",
       " \n",
       "        [[    1, 18458, 11618,  3343,  1509, 28404, 28404, 21862, 17578,\n",
       "          10977, 10977, 16441, 21229, 21229, 21229, 14411, 21671, 21671,\n",
       "          21671, 11295, 31557, 31557, 31557, 31557, 21248, 21248, 21248,\n",
       "          21248,  2403,  2403,  2403,  2060,  2060, 22179, 22179, 16479,\n",
       "          18313]],\n",
       " \n",
       "        [[    1,  5810,  2748, 27155,  5146, 27155,  7143,  7143, 20850,\n",
       "          26002,  3322,  3322,  9349,  9349, 28592, 28592,  7483,  7483,\n",
       "           7483, 19076,  6089,  6089,  6089,  6089,   911, 21204, 25057,\n",
       "          25057, 25057, 25057, 25057, 25057, 25057, 25057, 14103, 14103,\n",
       "          14103]],\n",
       " \n",
       "        [[    1, 27084, 12576, 16215, 16215,  8161,  2146,  8730,  8730,\n",
       "          11113, 10088, 10088, 10088, 10088, 10088,   655,   655,   655,\n",
       "            655, 24171, 24171,  7517,  9209, 10502, 10502, 22122,  6575,\n",
       "           6890, 24896, 24896, 24896, 14128, 24896, 24181, 24181, 24181,\n",
       "          29239]],\n",
       " \n",
       "        [[    1, 11917, 11309, 29918, 27692, 27692,  4491, 21722, 11930,\n",
       "          11930, 22198, 22198, 31649, 30513, 30513, 30513, 31109, 31109,\n",
       "          29073, 20340, 20340, 29248, 20522, 20522, 20522, 11281, 11281,\n",
       "          11281, 23090, 11281, 23090, 11281, 31946, 31946, 10449, 10449,\n",
       "          22265]],\n",
       " \n",
       "        [[    1, 15119, 17204, 16128, 16128, 17805, 26834, 26834, 26834,\n",
       "          23776, 30759, 30759,  7642,  7642,   505,   505,   505, 30118,\n",
       "          26259, 26259, 24811, 24811, 24811, 24811, 18579, 18579, 18579,\n",
       "          28695, 22035, 22035, 22035, 22035, 22035, 22035,  6106, 16752,\n",
       "          16752]],\n",
       " \n",
       "        [[    1, 23424, 30616, 17990, 17990, 25905,  5303,  1707, 25357,\n",
       "          25357, 25694, 28151, 11939, 11939, 11939, 11206, 11206, 11206,\n",
       "          25392, 11283, 21879, 21879, 21879, 22502,  6230, 11076, 11076,\n",
       "          12883,  7152,  7152,  7152,  7152, 27671, 20468, 20468, 20468,\n",
       "          20468]],\n",
       " \n",
       "        [[    1, 13302, 13302, 20484, 20484, 28214, 16964, 16964, 16964,\n",
       "          13056, 13056, 13056,  4479,  4479, 23593, 23593, 23593, 23593,\n",
       "          23593,  9637,  2292,  2292,  9637,  9637, 14551, 14551, 14551,\n",
       "           8659,  8659,  1281,  1281,  1739,  1739,  4399,  4399, 13485,\n",
       "          13485]]], dtype=int32), 10.373304, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:30<00:00,  2.74it/s, accuracy=0.131, cost=6.48]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.25it/s, accuracy=0.118, cost=6.32]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.997737, training avg acc 0.115513\n",
      "epoch 1, testing avg loss 6.376860, testing avg acc 0.143623\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:30<00:00,  2.74it/s, accuracy=0.151, cost=5.75]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.43it/s, accuracy=0.151, cost=5.82]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 5.996195, training avg acc 0.158967\n",
      "epoch 2, testing avg loss 5.832482, testing avg acc 0.163694\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:28<00:00,  2.75it/s, accuracy=0.174, cost=5.14]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.53it/s, accuracy=0.161, cost=5.56]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.453008, training avg acc 0.177577\n",
      "epoch 3, testing avg loss 5.564085, testing avg acc 0.171357\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.208, cost=4.62]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.59it/s, accuracy=0.161, cost=5.39]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.071127, training avg acc 0.193410\n",
      "epoch 4, testing avg loss 5.490453, testing avg acc 0.170616\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:12<00:00,  2.83it/s, accuracy=0.246, cost=4.19]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.49it/s, accuracy=0.167, cost=5.23]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.775139, training avg acc 0.208473\n",
      "epoch 5, testing avg loss 5.442450, testing avg acc 0.172700\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:12<00:00,  2.83it/s, accuracy=0.272, cost=3.83]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.50it/s, accuracy=0.172, cost=5.25]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.536215, training avg acc 0.223579\n",
      "epoch 6, testing avg loss 5.479210, testing avg acc 0.174521\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:12<00:00,  2.83it/s, accuracy=0.304, cost=3.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.58it/s, accuracy=0.183, cost=5.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.349116, training avg acc 0.238296\n",
      "epoch 7, testing avg loss 5.527614, testing avg acc 0.171947\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:18<00:00,  2.80it/s, accuracy=0.313, cost=3.45]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.58it/s, accuracy=0.156, cost=5.33]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.181607, training avg acc 0.253724\n",
      "epoch 8, testing avg loss 5.601341, testing avg acc 0.169663\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.313, cost=3.45]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.53it/s, accuracy=0.167, cost=5.33]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.035230, training avg acc 0.268918\n",
      "epoch 9, testing avg loss 5.611936, testing avg acc 0.168239\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.372, cost=3.03]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.53it/s, accuracy=0.183, cost=5.35]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 3.911519, training avg acc 0.281984\n",
      "epoch 10, testing avg loss 5.709213, testing avg acc 0.165553\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:13<00:00,  2.82it/s, accuracy=0.395, cost=2.9] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.51it/s, accuracy=0.151, cost=5.59]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.800369, training avg acc 0.294759\n",
      "epoch 11, testing avg loss 5.875114, testing avg acc 0.166193\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:13<00:00,  2.82it/s, accuracy=0.406, cost=2.83]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.58it/s, accuracy=0.177, cost=5.58]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.687886, training avg acc 0.309033\n",
      "epoch 12, testing avg loss 5.919628, testing avg acc 0.160217\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.388, cost=2.9] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.58it/s, accuracy=0.177, cost=5.51]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.592079, training avg acc 0.321279\n",
      "epoch 13, testing avg loss 5.920069, testing avg acc 0.157590\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.448, cost=2.6] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.53it/s, accuracy=0.14, cost=5.52] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.511723, training avg acc 0.331564\n",
      "epoch 14, testing avg loss 6.092453, testing avg acc 0.161897\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:13<00:00,  2.82it/s, accuracy=0.425, cost=2.66]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.59it/s, accuracy=0.145, cost=6.16]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.432869, training avg acc 0.342203\n",
      "epoch 15, testing avg loss 6.259332, testing avg acc 0.161507\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.47, cost=2.48] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  6.70it/s, accuracy=0.167, cost=6.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.351351, training avg acc 0.354476\n",
      "epoch 16, testing avg loss 6.371625, testing avg acc 0.160701\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:13<00:00,  2.82it/s, accuracy=0.518, cost=2.29]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.54it/s, accuracy=0.183, cost=5.92]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.275789, training avg acc 0.365444\n",
      "epoch 17, testing avg loss 6.471564, testing avg acc 0.160807\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.511, cost=2.33]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.62it/s, accuracy=0.161, cost=5.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.209314, training avg acc 0.375652\n",
      "epoch 18, testing avg loss 6.432416, testing avg acc 0.155843\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.484, cost=2.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.54it/s, accuracy=0.172, cost=5.92]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.150897, training avg acc 0.384714\n",
      "epoch 19, testing avg loss 6.394691, testing avg acc 0.154208\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:13<00:00,  2.82it/s, accuracy=0.543, cost=2.19]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.56it/s, accuracy=0.134, cost=6.04]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.093697, training avg acc 0.393676\n",
      "epoch 20, testing avg loss 6.538993, testing avg acc 0.152749\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [02:36<00:00,  3.92s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.048261568"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
